<template>
  <div class="article-manager">
    <div class="i-layout-page-header">
      <PageHeader class="product_tabs" title="" hidden-breadcrumb>
        <div slot="content">
          <Tabs v-model="artFrom.type" @on-click="onClickTab">
            <TabPane
              :label="item.name + '(' + item.count + ')'"
              :name="item.type.toString()"
              v-for="(item, index) in headeNum"
              :key="index"
            />
          </Tabs>
        </div>
      </PageHeader>
    </div>

    <Card :bordered="false" dis-hover class="ivu-mt">
      <Form
        ref="artFrom"
        :model="artFrom"
        :label-width="labelWidth"
        :label-position="labelPosition"
        @submit.native.prevent
      >
        <Row type="flex" :gutter="24">
          <Col v-bind="grid">
            <FormItem label="所属城市：" label-for="pid">
              <Select v-model="artFrom.city_id"  @on-change="selectCity" placeholder="请选择所属城市">
                  <Option v-for="item in cityList" :value="item.city_id" :key="item.city_id">{{ item.city_name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col v-bind="grid">
            <FormItem label="所属公司：" label-for="pid">
              <Select v-model="artFrom.company_id"   placeholder="请选择所属公司">
                  <Option v-for="item in companyList" :value="item.id" :key="item.id">{{ item.company_name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col v-bind="grid">
            <!-- 线路特性1:校园通勤2:高铁专线3:高校出行4:景区直通5:企业通勤，6品质公交7，红色专线 -->
            <FormItem label="线路特性：" label-for="pid">
              <Select v-model="artFrom.trait"   placeholder="请选择线路特性">
                <Option label="所有" :value="0" />
                <Option label="校园通勤" :value="1" />
                <Option  label="高铁专线" :value="2" />
                <Option label="高校出行" :value="3" />
                <Option label="景区直通" :value="4" />
                <Option label="企业通勤" :value="5" />
                <Option label="品质公交" :value="6" />
                <Option label="红色专线" :value="7" />
                    
              </Select>
            </FormItem>
          </Col>
          <Col v-bind="grid">
            <FormItem label="线路搜索：" label-for="line_name">
              <Input
                search
                enter-button
                placeholder="请输入线路名称,关键字,ID"
                v-model="artFrom.line_name"
                @on-search="userSearchs"
              />
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div class="Button">
        <router-link
          v-auth="['line-custom-bus-save']"
          :to="'/admin/line/add_coustom_bus'"
          ><Button type="primary" class="bnt mr15" icon="md-add"
            >添加线路</Button
          ></router-link>
      
        <Tooltip content="导出数据" :disabled="!!tableList.length">
          <Button
            class="export"
            icon="ios-share-outline"
            @click="exports"
            >导出</Button
          >
        </Tooltip>
      </div>
      <Table
        ref="table"
        :columns="columns"
        :data="tableList"
        class="ivu-mt"
        :loading="loading"
        highlight-row
        no-data-text="暂无数据"
        no-filtered-data-text="暂无筛选结果"
      >
      <template slot-scope="{ row, index }" slot="detail">
        <a @click="lookDetail(row)">详情</a>
      </template>
        <template slot-scope="{ row, index }" slot="priceList">
          <a @click="lookPrice(row)">查看价格</a>
        </template>
        <template slot-scope="{ row, index }" slot="action">
          <a @click="edit(row)">编辑</a>
          <Divider type="vertical" />
           <a v-if="row.status==1" @click="changeLineStatusClick('remove',row)">下线</a>        
           <a v-else @click="changeLineStatusClick('add',row)">上线</a>
          <Divider type="vertical" />
          <a  style="color:red" @click="changeLineStatusClick('delete',row)">{{row.status!=3?'删除':''}}</a>        
        </template>
        <template slot-scope="{ row, index }" slot="sort">
          <InputNumber  :min="0" v-model="row.sort" @on-change="changeSort(row)"></InputNumber>
        </template>
      </Table>
      <div class="acea-row row-right page">
        <Page
          :total="total"
          :current="artFrom.page" 
          show-elevator
          show-total
          @on-change="pageChange"
          :page-size="artFrom.limit"
        />
      </div>

      <!-- 价格列表 -->
      <Modal title="价格列表" width="35%" v-model="priceListVisible" ok-text="保存" 	 scrollable   :mask-closable="false"  :z-index="1"  @on-cancel="closePriceForm()"  @on-ok="submPriceForm()" >
        <Row  justify="space-between" style="justify-content: center;">
    
          <div style="display: flex;flex-direction: column;margin-bottom: 40px;align-items: center;margin-top:40px">
               <div  v-for="(item, index) in priceList" :key="index" style="display: flex;flex-direction: row;margin-bottom:15px;justify-content: flex-start;align-items: center;">
                 <span style="color:red">*</span>
                 <div style="width: 240px;">{{item.on_stop_name}}-{{item.off_stop_name}}:</div>
                  <InputNumber :min="0" v-model="item.price" style='margin-left:15px' ></InputNumber>
               </div>
          </div>
      </Row>
      </Modal>
      <!-- 价格列表 -->
      <!-- 线路详情 -->
      <Modal title="线路详情" width="50%" v-model="lineDetailVisible" ok-text="保存" 	 scrollable   :mask-closable="false"  :z-index="1"  @on-cancel="closeDetailForm()"  @on-ok="submDetailForm()" >
          <Form
          ref="detailForm"
          :model="detailForm"
          :label-width="labelWidth"
          :label-position="labelPosition"
          @submit.native.prevent
          :rules="ruleValidate"
        >
          <Row :gutter="24" type="flex">
            <Col span="24">
            
                <FormItem label="线路名称：" prop="store_name" >
                  <Input
                    v-model="detailForm.store_name"
                    placeholder="请输入线路名称"
                    v-width="'35%'"
                  />
                </FormItem>
            </Col>
            <Col span="24">
              <FormItem label="封面图：" prop="image">
                <div class="pictrueBox" @click="modalPicTap('dan', 'danFrom')">
                  <div class="pictrue" v-if="detailForm.image">
                    <img v-lazy="detailForm.image" />
                    <Input
                      v-model="detailForm.image"
                      style="display: none"
                    ></Input>
                  </div>
                  <div class="upLoad acea-row row-center-wrapper" v-else>
                    <Input
                      v-model="detailForm.image"
                      style="display: none"
                    ></Input>
                    <Icon type="ios-camera-outline" size="26" />
                  </div>
                </div>
                <div class="tips">(345*345)</div>
              </FormItem>
            </Col>
            <Col span="24">
              <FormItem label="轮播图：" prop="slider_image">
                <div class="acea-row">
                  <div
                    class="pictrue"
                    v-for="(item, index) in detailForm.slider_image"
                    :key="index"
                    draggable="true"
                    @dragstart="handleDragStart($event, item)"
                    @dragover.prevent="handleDragOver($event, item)"
                    @dragenter="handleDragEnter($event, item)"
                    @dragend="handleDragEnd($event, item)"
                  >
                    <img v-lazy="item" />
                    <Button
                      shape="circle"
                      icon="md-close"
                      @click.native="handleRemove(index)"
                      class="btndel"
                    ></Button>
                  </div>
                  <div
                    v-if="detailForm.slider_image.length < 10"
                    class="upLoad acea-row row-center-wrapper"
                    @click="modalPicTap('duo')"
                  >
                    <Icon type="ios-camera-outline" size="26" />
                  </div>
                  <Input
                    v-model="detailForm.slider_image[0]"
                    style="display: none"
                  ></Input>
                </div>
                <div class="tips">(最多10张<br />750*750)</div>
              </FormItem>
            </Col>
             <!-- 产品详情-->
             <Col span="24">
              <FormItem label="产品详情：">
                <vue-ueditor-wrap
                  v-model="detailForm.description"
                  @beforeInit="addCustomDialog"
                  :config="myConfig"
                  style="width: 90%"
                ></vue-ueditor-wrap>
              </FormItem>
            </Col>
             <!-- 产品详情-->
          </Row>
        </Form>
      </Modal>
      <Modal
        v-model="modalPic"
        width="60%"
        scrollable
        footer-hide
        closable
        title="上传产品图"
        :mask-closable="false"
        :z-index="1"
      >
        <uploadPictures
          :isChoice="isChoice"
          @getPic="getPic"
          @getPicD="getPicD"
          :gridBtn="gridBtn"
          :gridPic="gridPic"
          v-if="modalPic"
        ></uploadPictures>
      </Modal>
      <!-- 线路详情 -->
    </Card>

  </div>
</template>

<script>
import toExcel from "../../../utils/Excel.js";
import { mapState } from "vuex";
import {adminInfoApi} from "@/api/setting"
import uploadPictures from "@/components/uploadPictures";
import VueUeditorWrap from "vue-ueditor-wrap";
import {
  getLineHeade,
  getLines,
  changeLineStatusApi,
  exportLineListApi,
  saveLinePrice,
  saveLineDetailApi,
  changeLineSortApi
} from "@/api/line";

import exportExcel from "@/utils/newToExcel.js";

export default {
  name: "custom_busList",
  components: { uploadPictures,VueUeditorWrap},
  computed: {
    ...mapState("admin/layout", ["isMobile"]),
    ...mapState("admin/userLevel", ["categoryId"]),
    labelWidth() {
      return this.isMobile ? undefined : 75;
    },
    labelPosition() {
      return this.isMobile ? "top" : "right";
    },
  },
  data() {
    return {
      modalPic: false,
      isChoice: "",
      picTit: "",
      tableIndex: 0,
      ruleValidate: {
        store_name: [
          { required: true, message: "请输入名称", trigger: "blur" },
        ],
        image: [{ required: true, message: "请上传产品图", trigger: "change" }],
        slider_image: [
          {
            required: true,
            message: "请上传轮播图",
            type: "array",
            trigger: "change",
          },
        ]
      },
      detailForm: {
        store_name: '',
        image: '',
        slider_image: [],
        description: ''
      },
      lineDetailVisible: false,
      priceListVisible: false,
      cityList: [],
      companyList:[],
      template: false,
      modals: false,
      myConfig: {
        autoHeightEnabled: false, // 编辑器不自动被内容撑高
        initialFrameHeight: 500, // 初始容器高度
        initialFrameWidth: "100%", // 初始容器宽度
        UEDITOR_HOME_URL: "/admin/UEditor/",
        serverUrl: "",
      },
      gridPic: {
        xl: 6,
        lg: 8,
        md: 12,
        sm: 12,
        xs: 12,
      },
      gridBtn: {
        xl: 4,
        lg: 8,
        md: 8,
        sm: 8,
        xs: 8,
      },
      grid: {
        xl: 6,
        lg: 8,
        md: 12,
        sm: 24,
        xs: 24,
      },
      artFrom: {
        page: 1,
        limit: 25,
        status: "1",
        excel: 0,
        line_sn: '',
        city_id: '',
        company_id: '',
        trait: 0,
      },
      list: [],
      tableList: [],
      headeNum: [],
      treeSelect: [],
      loading: false,
      columns: [
     
        {
          title: "线路ID",
          key: "line_id",
          width: 200,
        },
        {
          title: "线路编号",
          key: "line_sn",
          minWidth: 80,
        },
        {
          title: "线路名称",
          key: "line_name",
          minWidth: 260,
        },
        {
          title: "线路特性",
          key: "trait_desc",
          minWidth: 50,
        },
        {
          title: "座位类型",
          key: "seat_type_desc",
          minWidth: 50,
        },
        {
          title: "排序",
          slot: "sort",
          minWidth: 50,
        },
        {
          title: "票价(元)",
          key: "discount_price",
          minWidth: 90,
        },
        {
          title: "线路详情",
          slot: "detail",
          minWidth: 70,
        },
        {
          title: "价格列表",
          slot: "priceList",
          minWidth: 70,
        },
        {
          title: "状态",
          key: "status_desc",
          width: 100,
        },
        // {
        //   title: "状态",
        //   slot: "status",
        //   width: 100,
        //   filters: [
        //     {
        //       label: "上架",
        //       value: 1,
        //     },
        //     {
        //       label: "下架",
        //       value: 0,
        //     },
        //   ],
        //   filterMethod(value, row) {
        //     return row.is_show === value;
        //   },
        //   filterMultiple: false,
        // },
        {
          title: "操作",
          slot: "action",
          fixed: "right",
          minWidth: 220,
        },
      ],
      data: [],
      total: 0,
      attrTemplate: false,
      ids: [],
      display: "none",
      formSelection: [],
      selectionCopy: [],
      checkBox: false,
      isAll: -1,
      value1: [],
      priceList: [],
      lineId: '',
      images: [],
      // activeKey:1
    };
  },
  watch: {
    $route() {
      // if (this.$route.fullPath === "/admin/line/custom_bus_list?status=1") {
      //   this.getPath();
      // }
    },
    formSelection(value) {
      // this.checkBox = value.length === this.tableList.length;
    },
    tableList: {
      deep: true,
      handler(value) {
        value.forEach((item) => {
          this.formSelection.forEach((itm) => {
            if (itm.id === item.id) {
              item.checkBox = true;
            }
          });
        });
        const arr = this.tableList.filter((item) => item.checkBox);
        if (this.tableList.length) {
          this.checkBox = this.tableList.length === arr.length;
        } else {
          this.checkBox = false;
        }
      },
    },
  },
  created() {
  },
  mounted() {

    // if (this.$route.fullPath === "/admin/line/custom_bus_list?status=1") {
    //   this.getPath();
    // } else {
    //   this.getDataList();
    // }
    
     this.getAdminInfo()
    // this.getDataList();
  },
  methods: {

    // 点击产品图
    modalPicTap(tit, picTit, index) {
      this.modalPic = true;
      this.isChoice = tit === "dan" ? "单选" : "多选";
      this.picTit = picTit;
      this.tableIndex = index;
    },
    lookPrice(item){
      this.priceList = []
      this.lineId = ''
      if(item.linePrice.length==0){
        this.$Message.error('请先设置线路站点！')
        return;
      }
      item.linePrice.forEach(el => {
        el.price = parseFloat(el.price)
      })
      this.priceList = item.linePrice
      this.lineId = item.line_id
      this.priceListVisible = true
    },
    lookDetail(item){
      this.lineId = ''
      this.lineId = item.line_id
      this.lineDetailVisible = true
      this.detailForm = {
                          store_name: item.store_name?item.store_name:'',
                          image: item.image?item.image:'',
                          slider_image: item.slider_image.length>0?item.slider_image:[],
                          description: item.description?item.description:''
                        }
    },
    closeDetailForm(){
      this.lineDetailVisible = false
      this.detailForm = {
                          store_name: '',
                          image: '',
                          slider_image: [],
                          description: ''
                        }
    },

    submDetailForm(){
  
      saveLineDetailApi(this.lineId, this.detailForm).then(res => {
        this.detailForm = {
                          store_name: '',
                          image: '',
                          slider_image: [],
                          description: ''
                        }
            this.$Message.success('保存成功')
            this.getDataList();
          }).catch(error => {
            this.$Message.error(error)
          })
    },

    closePriceForm(){
      this.priceList = [],
      this.lineId = ''
      this.priceListVisible = false
    },

    submPriceForm(){
      // this.priceListVisible = false
      if(this.priceList.length&&this.lineId){
        var data = {
          line_id: this.lineId,
          price_list: this.priceList
        }
        saveLinePrice(data).then(res => {
            this.$Message.success('保存成功')
            this.getDataList();
          }).catch(error => {
            this.$Message.error(error)
          })
      } else {
         this.$Message.error('请添加线路站点')
      }

    },
 // 获取单张图片信息
 getPic(pc) {
      switch (this.picTit) {
        case "danFrom":
          this.detailForm.image = pc.att_dir;
          break;

      }
      this.modalPic = false;
      console.log(333,this.detailForm)

    },
    // 获取多张图信息
    getPicD(pc) {
      this.images = pc;
      this.images.map((item) => {
        this.detailForm.slider_image.push(item.att_dir);
        this.detailForm.slider_image = this.detailForm.slider_image.splice(
          0,
          10
        );
      });
      this.modalPic = false;
      console.log(555,this.detailForm)

    },
     // 添加自定义弹窗
     addCustomDialog(editorId) {
      window.UE.registerUI(
        "test-dialog",
        function (editor, uiName) {
          // 创建 dialog
          let dialog = new window.UE.ui.Dialog({
            iframeUrl: "/admin/widget.images/index.html?fodder=dialog",
            editor: editor,
            name: uiName,
            title: "上传图片",
            cssRules: "width:1200px;height:500px;padding:20px;",
          });
          this.dialog = dialog;
          let btn = new window.UE.ui.Button({
            name: "dialog-button",
            title: "上传图片",
            cssRules: `background-image: url(https://cdn.oss.9gt.net/prov1.1/1/icons.png);background-position: -726px -77px;`,
            onclick: function () {
              // 渲染dialog
              dialog.render();
              dialog.open();
            },
          });
          return btn;
        },
        37
      );
      window.UE.registerUI(
        "video-dialog",
        function (editor, uiName) {
          let dialog = new window.UE.ui.Dialog({
            iframeUrl: "/admin/widget.video/index.html?fodder=video",
            editor: editor,
            name: uiName,
            title: "上传视频",
            cssRules: "width:1000px;height:500px;padding:20px;",
          });
          this.dialog = dialog;
          let btn = new window.UE.ui.Button({
            name: "video-button",
            title: "上传视频",
            cssRules: `background-image: url(../../../assets/images/icons.png);background-position: -320px -20px;`,
            onclick: function () {
              // 渲染dialog
              dialog.render();
              dialog.open();
            },
          });
          return btn;
        },
        38
      );
    },
   // h获取管理员信息
    getAdminInfo(){
      adminInfoApi().then((res) => {
          this.cityList = res.data.admin_roles_info
          if(res.status==200){
             this.goodHeade(); this.getDataList();
          }
        })
        .catch((error) => {
          console.log(error)
          this.$Message.error(error.msg||'错误请求')
        });
    },
    // 移动
    handleDragStart(e, item) {
      this.dragging = item;
    },
    handleDragEnd(e, item) {
      this.dragging = null;
    },
    handleDragOver(e) {
      e.dataTransfer.dropEffect = "move";
    },
    handleDragEnter(e, item) {
      e.dataTransfer.effectAllowed = "move";
      if (item === this.dragging) {
        return;
      }
      const newItems = [...this.detailForm.slider_image];
      const src = newItems.indexOf(this.dragging);
      const dst = newItems.indexOf(item);
      newItems.splice(dst, 0, ...newItems.splice(src, 1));
      this.detailForm.slider_image = newItems;
    },
    handleRemove(i) {
      this.images.splice(i, 1);
      this.detailForm.slider_image.splice(i, 1);
    },
    changeSort(item){
      console.log(2222,item)
      if(item.sort == null || item.sort == ''){
        return ;
      }
      var post = {
        id: item.id,
        sort: item.sort

      }
      this.loading = true;
      changeLineSortApi(post).then((res) => {
         
          this.loading = false;
        })
        .catch((res) => {
          this.loading = false;
          this.$Message.error(res.msg);
        });
    },
      // 选择城市触发
    selectCity(id) {
      var city = {}
      this.cityList.forEach(function(item) {
        if (item.city_id === id) {
          city = item
        }
      })
      var that = this
      if (!city.company_ids) {
        that.$Message.error('该城市下没有公司,请前往维护管理添加公司！')
        return
      }
      that.companyList = city.company_list
    },

 
    // 数据导出；
    async exports() {
      let [th, filekey, data, fileName] = [[], [], [], ""];
      let formValidate = this.artFrom;
      let lebData = await this.getExcelData(formValidate);
  
      if (!fileName) fileName = lebData.filename;
      if (!filekey.length) {
        filekey = lebData.filekey;
      }
      if (!th.length) th = lebData.header;
      if (lebData.export.length) {
        data = data.concat(lebData.export);
      }

      exportExcel(th, filekey, fileName, data);
    },
    getExcelData(excelData) {
      return new Promise((resolve, reject) => {
        exportLineListApi(excelData).then((res) => {
          return resolve(res.data);
        });
      });
    },
    changeTemplate(e) {
      // this.template = e;
    },
    freight() {
      this.$refs.template.isTemplate = true;
    },
   
 
    // tab选择
    onClickTab(name) {
      this.artFrom.status = name;
      // this.columns2 = [...this.columns];
      // if (name !== "1" && name !== "2") {
      //   this.columns2.shift({
      //     type: "selection",
      //     width: 60,
      //     align: "center",
      //   });
      // }
      this.getDataList();
    },
  
    // 获取产品表单头数量
    goodHeade() {
      getLineHeade()
        .then((res) => {
          this.headeNum = res.data.list;
        })
        .catch((res) => {
          this.$Message.error(res.msg);
        });
    },
    // 线路列表；
    getDataList() {
      this.loading = true;
      getLines(this.artFrom)
        .then((res) => {
          let data = res.data;
          this.tableList = data.list.map((item) => {
            if (this.isAll === 1) {
              item.checkBox = true;
            } else {
              item.checkBox = false;
            }
            return item;
          });
          this.total = res.data.count;
          this.loading = false;
        })
        .catch((res) => {
          this.loading = false;
          this.$Message.error(res.msg);
        });
    },
    pageChange(status) {
      this.artFrom.page = status;
      this.getDataList();
      this.$refs.table.clearCurrentRow();
    },
    // 表格搜索
    userSearchs() {
      this.artFrom.page = 1;
      this.formSelection = [];
      this.getDataList();
    },
    
       changeLineStatusClick(type, item) {
      var that = this
     
     this.$Modal.confirm({
        title: '提示',
        content: '<p>您是否要更改线路状态?</p>',
        onOk: () => {
            changeLineStatusApi({ type: type, id: item.id }).then(res => {
                 that.goodHeade()
                 that.getDataList()
                 that.$Message.success('操作成功')
            }).catch(error => {
              console.log(error)
            })
        },
        onCancel: () => {
            this.$Message.info('Clicked cancel');
        }
    });

    },
    // 编辑
    edit(row) {
      this.$router.push({ path: "/admin/line/add_coustom_bus?id=" + row.id });
    },
    // 排序
    sortChanged(e) {
      this.artFrom[e.key] = e.order;
      this.getDataList();
    },
  },
};
</script>
<style scoped lang="stylus">
/deep/.ivu-modal-mask {
  z-index: 999 !important;
}

/deep/.ivu-modal-wrap {
  z-index: 999 !important;
}

.Box {
  >>> .ivu-modal-body {
    height: 700px;
    overflow: auto;
  }
}

.tabBox_img {
  width: 36px;
  height: 36px;
  border-radius: 4px;
  cursor: pointer;

  img {
    width: 100%;
    height: 100%;
  }
}

/deep/.ivu-table-cell-expand-expanded {
  margin-top: -6px;
  margin-right: 33px;
  transition: none;

  .ivu-icon {
    vertical-align: 2px;
  }
}

/deep/.ivu-table-header {
  // overflow visible
}

/deep/.ivu-table th {
  overflow: visible;
}

/deep/.select-item:hover {
  background-color: #f3f3f3;
}

/deep/.select-on {
  display: block;
}

/deep/.select-item.on {
  background: #f3f3f3;
}

.pictrueBox {
  display: inline-block;
}

.pictrueTab {
  width: 40px !important;
  height: 40px !important;
}

.pictrue {
  width: 60px;
  height: 60px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  margin-right: 15px;
  display: inline-block;
  position: relative;
  cursor: pointer;

  img {
    width: 100%;
    height: 100%;
  }

  .btndel {
    position: absolute;
    z-index: 1;
    width: 20px !important;
    height: 20px !important;
    left: 46px;
    top: -4px;
  }
}

.upLoad {
  width: 58px;
  height: 58px;
  line-height: 58px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  background: rgba(0, 0, 0, 0.02);
  cursor: pointer;
}

.curs {
  cursor: pointer;
}

.inpWith {
  width: 60%;
}

.labeltop {
  >>> .ivu-form-item-label {
    float: none !important;
    display: inline-block !important;
    margin-left: 120px !important;
    width: auto !important;
  }
}

.video-icon {
  background-image: url('https://cdn.oss.9gt.net/prov1.1/1/icons.png'); // cdn.oss.9gt.net/prov1.1/1/icons.png);
  background-color: #fff;
  background-position: -9999px;
  background-repeat: no-repeat;
}
</style>
